package psn.zjk.common.jdk.juc;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @USER white
 * @DATETIME 2021/1/28 21:08
 */
public class DiyBlockingQueue {

    List list = new LinkedList();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    int capacity;

    public DiyBlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public void add(Object o) throws InterruptedException {
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        writeLock.lock();
        try {
            while (list.size() == capacity) {
                wait();
            }
            list.add(o);
            notify();
        }  finally {
            writeLock.unlock();
        }
    }


    public Object take() throws InterruptedException {
        //如果是单个消费者（一般是单消费者），重入锁就够了
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        try {
            while (list.size() == 0) {
                wait();
            }
            return list.remove(0);
        }finally {
            readLock.unlock();
        }

    }

}
